﻿using System;
using System.Linq;
using exp = System.Linq.Expressions;

namespace ToyundaPhone.Helpers
{
	public static class PredicateBuilder
	{
		public static exp.Expression<Func<T, bool>> True<T> ()  { return f => true;  }
		public static exp.Expression<Func<T, bool>> False<T>() { return f => false; }

		public static exp.Expression<Func<T, bool>> Or<T>(this exp.Expression<Func<T, bool>> expr1, exp.Expression<Func<T, bool>> expr2)
		{
			var invokedExpr = exp.Expression.Invoke(expr2, expr1.Parameters.Cast<exp.Expression>());
			return exp.Expression.Lambda<Func<T, bool>>
				(exp.Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
		}

		public static exp.Expression<Func<T, bool>> And<T>(this exp.Expression<Func<T, bool>> expr1, exp.Expression<Func<T, bool>> expr2)
		{
			var invokedExpr = exp.Expression.Invoke(expr2, expr1.Parameters.Cast<exp.Expression>());
			return exp.Expression.Lambda<Func<T, bool>>
				(exp.Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
		}
	}
}
